package com.softserveinc.moviedbapp.widget;

import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;

import com.softserveinc.moviedbapp.R;
import com.softserveinc.moviedbapp.application.PreferenceInputValidator;

public class WidgetConfigurePreferenceActivity extends PreferenceActivity {

	static final String TAG = WidgetConfigurePreferenceActivity.class.getSimpleName();

	int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTheme(android.R.style.Theme_Black_NoTitleBar_Fullscreen);

		/* get the appWidgetId of the appWidget being configured */
		Intent launchIntent = getIntent();
		Bundle extras = launchIntent.getExtras();
		if (extras != null) {
			mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
		}

		/* If they gave us an intent without the widget id, just bail. */
		if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
			finish();
		}

		/* set the result for cancel first so if the user cancels, then the appWidget would not appear */
		Intent cancelResultValue = new Intent();
		cancelResultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
		setResult(RESULT_CANCELED, cancelResultValue);

		/* this view has a list view with id @android:id/list those prefs from above will be added to this layout */
		addPreferencesFromResource(R.xml.widget_preferences);
		setContentView(R.layout.movie_widget_configure);

		/* set listeners on numeric options */
		Preference updateMovie = getPreferenceScreen().findPreference("updateMovie");
		updateMovie.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

			@Override
			public boolean onPreferenceChange(final Preference preference, final Object newValue) {
				return PreferenceInputValidator.checkNumericalInput(WidgetConfigurePreferenceActivity.this, newValue,
						1, 9999);
			}
		});

		Preference updateList = getPreferenceScreen().findPreference("updateList");
		updateList.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

			@Override
			public boolean onPreferenceChange(final Preference preference, final Object newValue) {
				return PreferenceInputValidator.checkNumericalInput(WidgetConfigurePreferenceActivity.this, newValue,
						1, 9999);
			}
		});

		Preference movieResutsPreference = getPreferenceScreen().findPreference("limit_movie_results_widget");
		movieResutsPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

			@Override
			public boolean onPreferenceChange(final Preference preference, final Object newValue) {
				return PreferenceInputValidator.checkNumericalInput(WidgetConfigurePreferenceActivity.this, newValue,
						2, 30);
			}
		});

		findViewById(R.id.cancel_button).setOnClickListener(mOnClickListener);
		findViewById(R.id.create_button).setOnClickListener(mOnClickListener);
	}

	View.OnClickListener mOnClickListener = new View.OnClickListener() {
		@Override
		public void onClick(final View v) {

			if (v.getId() == R.id.cancel_button) {
				finish();
			} else {
				/* get user prefs from config form */

				/* store prefs for this widget */
				storeWidgetPreferences();

				// fire an update to display initial state of the widget

				PendingIntent updatePendingIntent = MovieWidgetProvider.createPendingIntent(
						WidgetConfigurePreferenceActivity.this, UpdateService.UPDATE_CONFIG_CHANGED, mAppWidgetId);
				try {
					Log.d(TAG, "trying to send intent to Service with " + UpdateService.UPDATE_CONFIG_CHANGED);
					updatePendingIntent.send();
				} catch (CanceledException e) {
					Log.e(TAG, "Error ", e);
				}
				// Make sure we pass back the original appWidgetId
				Intent resultValue = new Intent();
				resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
				setResult(RESULT_OK, resultValue);
				finish();
			}
		}

	};

	private void storeWidgetPreferences() {

		SharedPreferences defaultPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

		Integer updateNextMovie;
		try {
			updateNextMovie = new Integer(defaultPrefs.getString("updateMovie", "5"));
			if (updateNextMovie.intValue() < 1 || updateNextMovie.intValue() > 20000) {
				updateNextMovie = 5;
			}
		} catch (NumberFormatException ex) {
			Log.e(TAG, "updateNextMovie", ex);
			updateNextMovie = 5;
		}

		Integer updateMovieList;
		try {
			updateMovieList = new Integer(defaultPrefs.getString("updateList", "30"));
			if (updateMovieList.intValue() < 30 || updateMovieList.intValue() > 20000) {
				updateMovieList = 30;
			}
		} catch (NumberFormatException ex) {
			Log.e(TAG, "updateMovieList", ex);
			updateMovieList = 30;
		}

		String results = defaultPrefs.getString("limit_movie_results_widget", "10");

		String orderBy = defaultPrefs.getString("widget_order_by", "release");

		Log.d(TAG, "in storeWidgetPreferences() prefs:\n");
		Log.d(TAG, "updateNextMovie " + updateNextMovie + "\n");
		Log.d(TAG, "updateMovieList " + updateMovieList + "\n");
		Log.d(TAG, "orderBy " + orderBy + "\n");
		Log.d(TAG, "results " + results + "\n");

		SharedPreferences prefs = getSharedPreferences("widget_prefs", 0);
		SharedPreferences.Editor edit = prefs.edit();
		edit.putInt(WidgetPreferencesConstants.UPDATE_NEXT_MOVIE + mAppWidgetId, updateNextMovie);
		edit.putInt(WidgetPreferencesConstants.UPDATE_NEXT_LIST + mAppWidgetId, updateMovieList);
		edit.putString(WidgetPreferencesConstants.MOVIES_RESULTS + mAppWidgetId, results);
		edit.putString(WidgetPreferencesConstants.ORDER_BY + mAppWidgetId, orderBy);

		edit.commit();

	}
}
